<template>
	<div>
		<CustomDialog
			:title="state.dialog.title"
			v-model:visible="state.dialog.isShowDialog"
			dialogWidth="900px"
			@close="closeDialog"
			:dialogFooterBtn="true"
		>
			<el-form ref="discountDialogFormRef" :model="state.ruleForm" size="default" label-width="90px">
				<el-form-item label="活动名称" prop="activityName" :rules="{ required: true, message: '活动名称不能为空', trigger: 'blue' }">
					<el-input v-model="state.ruleForm.activityName" placeholder="请输入活动名称" clearable></el-input>
				</el-form-item>

				<el-form-item label="活动时间" prop="activityTime" :rules="{ required: true, message: '活动时间不能为空', trigger: 'blue' }">
					<el-date-picker
						v-model="state.ruleForm.activityTime"
						type="datetimerange"
						range-separator="至"
						start-placeholder="开始时间"
						end-placeholder="结束时间"
					/>
				</el-form-item>

				<el-form-item label="优惠类型" prop="discountType">
					<el-radio-group v-model="state.ruleForm.discountType" :disabled="state.discountTypeDisabled">
						<el-radio :label="0">按消费金额包邮</el-radio>
						<el-radio :label="1">按购买件数包邮</el-radio>
					</el-radio-group>
				</el-form-item>

				<el-form-item>
					<div class="acitivty-rule">
						<!-- <el-form label-position="left"> -->
						<div class="activity-rule-content">
							<el-form-item label="规则" label-width="50px">
								<el-row :gutter="5">
									<el-col :xs="24" :sm="8" :md="12" :lg="12" :xl="12" class="mb20">
										<el-form-item
											label="消费满"
											prop="discountContition.buy"
											:rules="{ required: true, message: '消费满多少件不能为空', trigger: 'blue' }"
										>
											<el-input v-model="state.ruleForm.discountContition.buy" type="number" step="0.1" min="0">
												<template #append>
													<div v-if="state.ruleForm.discountType == 0">元</div>
													<div v-else>件</div>
												</template>
											</el-input>
										</el-form-item></el-col
									>
									<el-col :xs="24" :sm="8" :md="8" :lg="8" :xl="8" class="mb20">
										<!--											<div class="exec-width" v-if="state.ruleForm.discountType == 0">满折金额优惠按照商品实际金额计算</div>-->
										<div class="exec-width">满邮金额优惠按照商品实际金额计算</div>
									</el-col>
								</el-row>
							</el-form-item>
						</div>
						<div class="activity-rule-content">
							<el-form-item label="不支持地区">
								<div>
									<div>
										<span v-for="(item, index) in state.areas" :key="index"> {{ item.name }},</span>
									</div>
									<el-button type="primary" link @click="addArea"> 添加地区 </el-button>
								</div>
							</el-form-item>
						</div>
						<!-- </el-form> -->
					</div>
				</el-form-item>

				<!-- </el-col> -->
				<!-- <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20"> -->
				<el-form-item label="活动说明" prop="activityDesc">
					<el-input v-model="state.ruleForm.activityDescTitle" placeholder="请选择活动说明">
						<template #append>
							<div class="cursor-pointer" @click="openRichTextDialog">选择活动说明</div>
						</template>
					</el-input>
				</el-form-item>
				<!-- </el-col> -->
				<!-- <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20"> -->
				<el-form-item label="活动商品" prop="activityRangeType">
					<el-radio-group v-model="state.ruleForm.activityRangeType">
						<el-radio :label="0">全部商品</el-radio>
						<el-radio :label="1">部分商品</el-radio>
					</el-radio-group>
				</el-form-item>

				<div class="activity-item" v-if="state.ruleForm.activityRangeType == 1">
					<el-form-item>
						<el-button type="primary" link @click="addItem"> +添加商品 </el-button>
					</el-form-item>
					<el-form-item>
						<div class="item-content">
							<div v-if="state.items.length > 0" class="flex item-header">
								<div class="content">商品信息</div>
								<div class="oper">操作</div>
							</div>
							<div>
								<div class="flex item-body" v-for="(item, index) in state.items">
									<div class="content flex">
										<div class="goods-img">
											<img :src="STATIC_URL + item.image" alt="" class="goods-img" />
										</div>
										<div class="goods-content">
											<div class="goods-title cursor-pointer" :title="item.title">{{ item.title }}</div>
											<div class="goods-price">{{ item.price }}元</div>
										</div>
									</div>
									<div class="oper">
										<el-button type="danger" link @click="removeItem(index)"> 移除 </el-button>
									</div>
								</div>
							</div>
						</div>
					</el-form-item>
				</div>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="default">取 消</el-button>
					<el-button type="primary" @click="onSubmit(discountDialogFormRef)" size="default">{{ state.dialog.submitTxt }}</el-button>
				</span>
			</template>
			<!-- </el-dialog> -->
		</CustomDialog>
		<ItemDialog ref="ItemChoiceRef" @choice="choiceItem"></ItemDialog>
		<AreaDialog ref="AreaChoiceRef" @choice="choiceArea"></AreaDialog>
		<ChoiceRichTextDialog ref="ChoiceRichTextDialogRef" @choice="choiceRichText"></ChoiceRichTextDialog>
	</div>
</template>

<script setup lang="ts">
import { reactive, ref, defineAsyncComponent } from 'vue';
import { type FormInstance, type FormRules } from 'element-plus';
import msg from '/@/utils/messageUtils';
import { STATIC_URL } from '/@/utils/config';
import { FreeShippingApi } from '/@/api/shop/free_shipping';
import _ from 'lodash';
const ItemDialog = defineAsyncComponent(() => import('/@/views/goods/goods/choice/index.vue'));
const AreaDialog = defineAsyncComponent(() => import('/@/views/shop/data/area/choice/index.vue'));
const ChoiceRichTextDialog = defineAsyncComponent(() => import('/@/views/shop/data/richtext/choice/index.vue'));
const ChoiceRichTextDialogRef = ref();
const ItemChoiceRef = ref();
const AreaChoiceRef = ref();
const discountDialogFormRef = ref();
const emit = defineEmits(['refresh']);
const state = reactive({
	ruleForm: {
		id: '',
		activityTime: [] as any,
		activityName: '',
		startTime: '',
		endTime: '',
		activityType: 1,
		discountType: 0,
		activityRangeType: 0,
		activityDescId: '',
		activityDescTitle: '',
		discountContition: { buy: 0 },
	},
	discountTypeDisabled: false,
	items: [] as any,
	areas: [] as ChoiceAreaData[],
	dialog: {
		isShowDialog: false,
		type: '',
		title: '',
		submitTxt: '',
	},
});

const rules = reactive<FormRules>({
	activityName: [{ required: true, message: '请输入活动名称', trigger: 'blur' }],
	activityTime: [{ required: true, message: '请选择活动时间 ', trigger: 'blur' }],
});

const onCancel = () => {
	closeDialog();
};

const deleteByConditionIndex = (index: number) => {
	// state.discountConditions.splice(index, 1);
};

const openRichTextDialog = () => {
	ChoiceRichTextDialogRef.value.openDialog();
};

const choiceRichText = (choiceRichText: ChoiceRichText) => {
	console.log('choiceRichText: ', choiceRichText);
	state.ruleForm.activityDescId = choiceRichText.id;
	state.ruleForm.activityDescTitle = choiceRichText.title;
};
const addArea = () => {
	let areaIds = state.areas.map((e: any) => e.id);
	console.log('areaIds: ', areaIds);
	AreaChoiceRef.value.openDialog(areaIds);
};

const choiceArea = (choiceAreaDatas: ChoiceAreaData[]) => {
	console.log('添加地区: ', choiceAreaDatas);
	state.areas = choiceAreaDatas;
};

const choiceItem = (choiceGoodsItems: ChoiceGoodsItem[]) => {
	console.log('choiceGoodsItem: ', choiceGoodsItems);
	choiceGoodsItems.forEach((item) => {
		state.items.push({
			id: item.id,
			image: item.image,
			title: item.title,
			price: item.price,
		});
	});
};

const removeItem = (index: number) => {
	state.items.splice(index, 1);
};

const addItem = () => {
	ItemChoiceRef.value.openDialog();
};
// 关闭弹窗
const closeDialog = () => {
	console.log('关闭窗口');
	state.dialog.isShowDialog = false;
	clearArraysContent();
	state.ruleForm.activityName = '';
	state.ruleForm.activityTime = [];
	state.discountTypeDisabled = false;
};

const onSubmit = async (formEl: FormInstance | undefined) => {
	const activityTime = state.ruleForm.activityTime;
	console.log('activityTime: ', activityTime);
	console.log('startTime:  ', activityTime[0]);
	if (!formEl) return;
	await formEl.validate(async (valid) => {
		if (valid) {
			try {
				const ids = state.items.map((e: any) => e.id);
				console.log('ids: ', ids);
				if (state.dialog.type === 'add') {
					await FreeShippingApi().create({
						activityName: state.ruleForm.activityName,
						activityStartTime: activityTime[0].getTime(),
						activityEndTime: activityTime[1].getTime(),
						discountType: state.ruleForm.discountType,
						discountContent: state.ruleForm.discountContition,
						activityRangeType: state.ruleForm.activityRangeType,
						areas: state.areas,
						contentIds: ids,
						activityDescId: state.ruleForm.activityDescId,
						activityDescTitle: state.ruleForm.activityDescTitle,
					});
				} else {
					resolveTime(activityTime[0]);
					resolveTime(activityTime[1]);
					await FreeShippingApi().update({
						id: state.ruleForm.id,
						activityName: state.ruleForm.activityName,
						activityStartTime: resolveTime(activityTime[0]),
						activityEndTime: resolveTime(activityTime[1]),
						discountType: state.ruleForm.discountType,
						discountContent: state.ruleForm.discountContition,
						activityRangeType: state.ruleForm.activityRangeType,
						areas: state.areas,
						contentIds: ids,
						activityDescId: state.ruleForm.activityDescId,
						activityDescTitle: state.ruleForm.activityDescTitle,
					});
				}
				msg().success('操作成功');
				closeDialog();
				emit('refresh');
			} catch (e) {
				console.log('e: ', e);
				msg().error('操作失败');
			}
		}
	});
};

const openDialog = async (type: string, id: string) => {
	if (type === 'edit') {
		state.dialog.title = '修改包邮活动';
		state.dialog.submitTxt = '修 改';
		state.dialog.type = 'edit';
		state.ruleForm.id = id;
		console.log('id: ', id);
		const { data } = await FreeShippingApi().view(id);
		console.log('data: ', data);
		state.discountTypeDisabled = true;
		state.ruleForm.id = id;
		state.ruleForm.activityName = data.activityName;
		state.ruleForm.activityRangeType = data.activityRangeType;
		state.ruleForm.activityTime = [data.activityStartTime, data.activityEndTime];
		state.ruleForm.discountType = data.discountType;
		if (data.activityRangeType == 1) {
			state.items = data.activityItemVOS;
		}
		state.ruleForm.discountContition = data.freeShippingDiscountContentVO;
		state.areas = data.freeShippingRegionNotSupportVOs;
		state.ruleForm.activityDescId = data.activityDescId;
		state.ruleForm.activityDescTitle = data.activityDescTitle;
	} else {
		state.dialog.title = '新增包邮活动';
		state.dialog.submitTxt = '新 增';
		state.dialog.type = type;

		state.discountTypeDisabled = false;

		// nextTick(() => {
		// 	discountDialogFormRef.value.resetFields();
		// 	discountDialogFormRef.value.clearValidate();
		// });
		state.ruleForm.activityName = '';
		state.ruleForm.activityTime = [];
	}
	state.dialog.isShowDialog = true;
};

const resolveTime = (time: any) => {
	const contentType = typeof time;

	if (contentType == 'string') {
		console.log('time: ', time, ' is string');
		return new Date(time).getTime();
	}
	return time;
};

const clearArraysContent = () => {
	state.items = [];
	state.areas = [];
	state.ruleForm.discountType = 0;
	state.ruleForm.activityRangeType = 0;
	state.ruleForm.discountContition = { buy: 0 };
};
defineExpose({ openDialog });
</script>

<style scoped>
.item-content {
	width: 400px;
}

.exec-width {
	width: 250px;
	margin-left: 10px;
}

.item-header {
	background-color: rgba(223, 230, 233, 1);
}

.item-body {
	margin-top: 10px;
}
.content {
	flex: 1;
}

.oper {
	width: 60px;
}

.goods-img {
	width: 50px;
	height: 50px;
}

.goods-content {
	margin-left: 10px;
	flex: 1;
	.goods-title {
		font-size: 14px;
		height: 20px;
		line-height: 20px;
		overflow: hidden;
		text-overflow: ellipsis;
		/* white-space: nowrap; */
		/* text-overflow: ellipsis; */
		display: -webkit-box;
		-webkit-line-clamp: 1;
		-webkit-box-orient: vertical;
		padding-right: 5px;
	}
	.goods-price {
		font-size: 12px;
		height: 20px;
		line-height: 40px;
		color: rgba(255, 118, 117, 1);
	}
}
</style>
